package com.lottery.pay.Utils.wxUtil;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.Map.Entry;

public class MainUtil {

	public static final Logger logger = LoggerFactory.getLogger(MainUtil.class);

	/**
	 * 验证签名
	 * 
	 */
	public static boolean checkSignature(String token, String signature,
                                         String timestamp, String nonce) {
		String[] arr = { token, timestamp, nonce };
		// 将 token, timestamp, nonce 三个参数进行字典排序
		Arrays.sort(arr);
		StringBuilder content = new StringBuilder();
		for (int i = 0; i < arr.length; i++) {
			content.append(arr[i]);
		}
		MessageDigest md = null;
		String tmpStr = null;

		try {
			md = MessageDigest.getInstance("SHA-1");
			// 将三个参数字符串拼接成一个字符串进行 shal 加密
			byte[] digest = md.digest(content.toString().getBytes());
			tmpStr = byteToStr(digest);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		content = null;
		// 将sha1加密后的字符串可与signature对比，标识该请求来源于微信
		return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) : false;
	}

	/**
	 * 生成js-sdk签名
	 */
	public static String creatJsSign(JsParam jsParam) {
		StringBuffer sb = new StringBuffer();
		sb.append("jsapi_ticket=" + jsParam.getJsapi_ticket() + "&");
		sb.append("noncestr=" + jsParam.getNoncestr() + "&");
		sb.append("timestamp=" + jsParam.getTimestamp() + "&");
		sb.append("url=" + jsParam.getUrl());
		String sign = null;
		try {
			MessageDigest md = MessageDigest.getInstance("SHA-1");
			byte[] digest = md.digest(sb.toString().getBytes());
			sign = byteToStr(digest);
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return sign.toLowerCase();
	}

	/**
	 * 生成微信支付签名
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static String creatSign(TreeMap<Object, Object> treeMap,
                                   String apiKey) {
		StringBuffer sb = new StringBuffer();
		Set<Entry<Object, Object>> es = treeMap.entrySet();// 按键值名ASCII码从小到大排序
		Iterator<Entry<Object, Object>> it = es.iterator();
		while (it.hasNext()) {
			Entry entry = (Entry) it.next();
			String k = (String) entry.getKey();
			Object v = entry.getValue();
			if (null != v && !"".equals(v) && !"sign".equals(k)
					&& !"key".equals(k)) {
				sb.append(k + "=" + v + "&");
			}
		}
		sb.append("key=" + apiKey);
		logger.info(" creat sign is {}",sb.toString());
		String sign = MD5Util.encode(sb.toString()).toUpperCase();
		return sign;
	}

	/**
	 * 将字节数组转换为十六进制字符串
	 *
	 * @param digest
	 * @return
	 */
	private static String byteToStr(byte[] digest) {
		String strDigest = "";
		for (int i = 0; i < digest.length; i++) {
			strDigest += byteToHexStr(digest[i]);
		}
		return strDigest;
	}

	/**
	 * 将字节转换为十六进制字符串
	 *
	 * @param b
	 * @return
	 */
	private static String byteToHexStr(byte b) {
		char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
				'B', 'C', 'D', 'E', 'F' };
		char[] tempArr = new char[2];
		tempArr[0] = Digit[(b >>> 4) & 0X0F];
		tempArr[1] = Digit[b & 0X0F];

		String s = new String(tempArr);
		return s;
	}

	/**
	 * 将ISO8859_1编码转换utf-8
	 *
	 */
	public static String encodedTransToUTF(String pamar) {
		String newPamar = null;
		try {
			newPamar = new String(pamar.getBytes("ISO8859_1"), "utf-8");
		} catch (UnsupportedEncodingException e) {
			logger.info("编码转换错误:{}", e);
		}
		return newPamar;
	}

	/**
	 * 将utf-8编码转换ISO8859_1
	 *
	 */
	public static String encodedTransToISO(String pamar) {
		String newPamar = null;
		try {
			newPamar = new String(pamar.getBytes("utf-8"), "ISO8859_1");
		} catch (UnsupportedEncodingException e) {
			logger.info("编码转换错误:{}", e);
		}
		return newPamar;
	}

	/**
	 * 将Object转为TreeMap
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static TreeMap<Object, Object> objectToTreeMap(Object object) {
		String objectString = JSON.toJSONString(object);
		Map<Object, Object> map = (Map<Object, Object>) JSON
				.parse(objectString);
		TreeMap<Object, Object> treeMap = new TreeMap<Object, Object>();
		Set<Entry<Object, Object>> es = map.entrySet();
		Iterator<Entry<Object, Object>> it = es.iterator();
		while (it.hasNext()) {
			Entry entry = (Entry) it.next();
			String k = (String) entry.getKey();
			Object v = entry.getValue();
			treeMap.put(k, v);
		}
		return treeMap;
	}
}
